<template>
  <div class="container">
    <el-form :model="param" :inline="true" class="newForm">
      <el-row>
        <el-col :span="18">
          <el-form-item label="新闻标题">
            <el-input v-model="param.title" placeholder="请输入新闻标题" class="title"></el-input>
          </el-form-item>
          <el-form-item label="状态">
            <el-select v-model="param.status" placeholder="请选择状态">
              <el-option label="禁用" :value="0"></el-option>
              <el-option label="启用" :value="1"></el-option>
            </el-select>
          </el-form-item>
          <el-form-item label="审核状态">
            <el-select v-model="param.auditStatus" placeholder="请选择审核状态">
              <el-option label="待审核" :value="0"></el-option>
              <el-option label="审核通过" :value="1"></el-option>
              <el-option label="审核未通过" :value="2"></el-option>
            </el-select>
          </el-form-item>
        </el-col>
        <el-col :span="6" style="text-align:right;">
          <el-form-item>
            <el-button type="primary" @click="search">查询</el-button>
            <el-button type="primary" @click="reset">重置</el-button>
            <el-button type="primary" @click="addAD">添加</el-button>
          </el-form-item>
        </el-col>
      </el-row>
    </el-form>
    <el-row class="auth_box">
      <el-button type="info" @click="toExamine">批量审核</el-button>
      <!-- <el-button type="info" @click="batchAudit">批量审核</el-button> -->
      <el-button type="info" @click="del">删除</el-button>
    </el-row>
    <el-table ref="multipleTable" :data="tableData" tooltip-effect="dark" style="width: 100%" align="center"
      @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="55"></el-table-column>
      <el-table-column prop="title" label="新闻标题" show-overflow-tooltip></el-table-column>
      <el-table-column prop="noticeTime" label="发布时间"></el-table-column>
      <el-table-column prop="areaName" label="发布区域"></el-table-column>
      <el-table-column label="状态" width="80">
        <template slot-scope="scope">
          <el-switch v-model="scope.row.status" :active-value="1" :inactive-value="0" @change="updateStatus(scope.row)">
          </el-switch>
        </template>
      </el-table-column>
      <el-table-column label="审核状态" prop="auditStatusName" width="100"></el-table-column>
      <el-table-column prop="auditCause" label="审核原因" show-overflow-tooltip></el-table-column>
      <!-- <el-table-column prop="createTime" label="创建时间"></el-table-column> -->
      <el-table-column label="操作">
        <template slot-scope="scope">
          <el-button @click="toExamine(scope.row)" type="text" size="small">审核</el-button>
          <el-button @click="updateNEW(scope.row)" type="text" size="small">修改</el-button>
          <el-button type="text" size="small" @click="delSign(scope.row)" class="red">删除</el-button>
        </template>
      </el-table-column>
    </el-table>
    <div class="page">
      <el-pagination background @size-change="handleSizeChange" @current-change="handleCurrentChange"
        :current-page="param.page" :page-sizes="[10,30,60,100,200,300]" :page-size="param.size"
        layout="prev, pager, next, jumper, sizes, total" :total="param.total"></el-pagination>
    </div>

    <!-- 审核弹框 -->
    <el-dialog :visible.sync="toExamineVisible" width="40%" class="elDialog" :before-close="handleClose">
      <p slot="title" class="elDialog-header">
        <span>{{toExamineTxt}}</span>
      </p>
      <div class="elDialog-content">
        <el-form :model="toExamineForm" :inline="true" ref="toExamineForm" :rules="toExamineRules" label-width="135px"
          style="width:100%">
          <el-form-item label="审核结果：" prop="auditStatus">
            <el-radio-group v-model="toExamineForm.auditStatus" @change="auditStatusChange">
              <el-radio label="1">通过</el-radio>
              <el-radio label="2">不通过</el-radio>
              <el-radio label="0">待定</el-radio>
            </el-radio-group>
          </el-form-item>
          <el-form-item label="审核不通过原因：" v-if="toExamineForm.auditStatus==2" prop="auditCause">
            <el-input type="textarea" v-model="toExamineForm.auditCause" placeholder="请输入审核不通过原因"></el-input>
          </el-form-item>
        </el-form>
      </div>
      <div slot="footer" class="dialog-footer">
        <el-button @click="resetForm('toExamineForm')">取 消</el-button>
        <el-button type="primary" @click="saveToExamine('toExamineForm')">确 定</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { newsList, Newupdatestatus, delNew, delAllNEWS, auditStatus } from '../../../api/content';
import bus from '../../common/bus.js'

export default {
  name: 'news',
  data () {
    return {
      // 控制审核弹框开关
      toExamineVisible: false,
      param: {
        page: 1,
        size: 10,
        title: '',
        status: '',
        total: 0,
        // 审核状态
        auditStatus: '',
      },
      tableData: [],
      selection: [],
      // 审核form表单
      toExamineForm: {
        // 审核结果
        auditStatus: '',
        // 审核不通过原因
        auditCause: ''
      },
      toExamineRules: {
        auditStatus: [{ required: true, message: '请选择审核结果', trigger: 'change' }],
        auditCause: [
          { required: true, message: '请输入不通过原因', trigger: 'blur' },
          { min: 0, max: 500, message: '不通过原因长度在 0 到 500 个字符' }
        ]
      },
      // 单个审核id
      singleId: '',
      // 审核弹框标题
      toExamineTxt: ''
    };
  },
  created () {
    if (this.$route.query.auditStatus == 0) {
      this.param.auditStatus = Number(this.$route.query.auditStatus)
    }
    this.newsList();
  },
  watch: {
    '$route.fullPath': function (val, oldVal) {
      this.$nextTick(() => {
        if (this.$route.query.auditStatus == 0) {
          this.param.auditStatus = Number(this.$route.query.auditStatus)
          this.newsList();
        }
      })
    }
  },
  methods: {
    newsList () {
      let temp =
        '?page=' + this.param.page + '&size=' + this.param.size + '&title=' + this.param.title + '&status=' + this.param.status + '&auditStatus=' + this.param.auditStatus;
      newsList(temp).then(data => {
        console.log(data);
        if (data.success) {
          this.tableData = data.data.records;
          this.param.total = data.data.total;
        } else {
          this.$message.error(`${data.msg}`);
        }
      });
    },
    search () {
      this.param.page = 1;
      this.newsList();
    },
    reset () {
      this.param.title = '';
      this.param.status = '';
      this.param.auditStatus = '';
      this.param.page = 1;
      this.size = 10;
      this.newsList();
    },
    addAD () {
      this.$router.push({ path: '/addEditNews' });
    },
    del () {
      if (this.selection.length < 1) {
        this.$message.error('请选择想要删除的新闻!');
      } else {
        this.$confirm('您要删除新闻，删除后不可恢复，是否确定操作？', '信息提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning',
          callback: action => {
            if (action === 'confirm') {
              let arr = [];
              this.selection.map(item => arr.push(item.id));
              delAllNEWS(arr).then(data => {
                console.log(data);
                if (data.success) {
                  this.$message.success('删除成功');
                  this.newsList();
                } else {
                  this.$message.error(`${data.msg}`);
                }
              });
            }
          }
        });
      }
    },
    delSign (row) {
      this.$confirm('您要删除这条新闻，删除后不可恢复，是否确定操作？', '信息提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning',
        callback: action => {
          if (action === 'confirm') {
            delNew(row.id).then(data => {
              if (data.success) {
                this.$message.success('删除成功');
                this.newsList();
              } else {
                this.$message.error(`${data.msg}`)
              }
            });
          }
        }
      });
    },
    handleSizeChange (val) {
      this.param.size = val;
      this.newsList();
    },
    handleCurrentChange (val) {
      this.param.page = val;
      this.newsList();
    },
    handleSelectionChange (selected) {
      this.selection = selected;
    },
    updateStatus (row) {
      let temp = '/' + row.id + '/' + row.status;
      Newupdatestatus(temp).then(data => {
        if (!data.success) {
          this.$message.error(`${data.msg}`);
          this.newsList();
        }
      });
    },
    updateNEW (row) {
      // bus.$emit('openTags', { fullPath: `/addEditNews?id=${row.id}`, meta: { title: row.title } })
      this.$router.push({ path: '/addEditNews?id=' + row.id });
    },
    // 单个审核
    toExamine (row) {
      if (row.id) { // 单个审核
        // this.toExamineForm.auditCause = row.auditCause;
        // switch (row.auditStatusName) {
        //   case '待审核':
        //     this.toExamineForm.auditStatus = '0';
        //     break;
        //   case '审核通过':
        //     this.toExamineForm.auditStatus = '1';
        //     break;
        //   case '审核未通过':
        //     this.toExamineForm.auditStatus = '2';
        //     break;
        // }
        this.singleId = row.id;
        this.toExamineTxt = '审核';
        this.toExamineVisible = true;
      } else { // 多个审核
        if (this.selection.length < 1) {
          this.$message.error('请选择想要审核的新闻广告!');
        } else {
          this.toExamineTxt = '批量审核';
          this.toExamineVisible = true;
        }
      }
    },
    // 批量审核
    // batchAudit () {
    //   if (this.selection.length < 1) {
    //     this.$message.error('请选择想要审核的新闻广告!');
    //   } else {
    //     this.toExamineTxt = '批量审核';
    //     this.toExamineVisible = true;
    //   }
    // },
    // 保存审核信息
    saveToExamine (formName) {
      this.$refs[formName].validate((valid) => {
        if (valid) {
          //  调用审核方法
          this.getExamineForm()
        } else {
          console.log('error submit!!');
          return false;
        }
      });
    },
    // 审核表单提交
    getExamineForm () {
      let ids = [];
      if (this.toExamineTxt == '审核') { // 单个审核
        ids.push(this.singleId);
      } else { // 批量审核
        this.selection.map(item => {
          ids.push(item.id)
        })
      }
      let obj = {
        auditStatus: this.toExamineForm.auditStatus,
        query: {
          auditCause: this.toExamineForm.auditCause,
          ids: ids
        }
      }
      // 审核接口
      auditStatus(obj).then(res => {
        if (res.success) {
          this.$message.success(`审核成功!`)
          this.toExamineVisible = false;
          this.newsList();
          this.handleClose()
        } else {
          this.$message.error(`${res.msg}`)
        }
      })
    },
    // 选择审核状态时 判断如果选中的不是未通过的就让不通过原因为空
    auditStatusChange (val) {
      if (val != '2') {
        this.toExamineForm.auditCause = '';
      }
    },
    // 关闭弹框回调
    handleClose () {
      this.$refs.toExamineForm.resetFields()
      this.toExamineVisible = false;
    },
    // 清空表单
    resetForm (formName) {
      this.$refs[formName].resetFields();
      this.toExamineVisible = false;
    },
    clearForm () {
      this.toExamineForm.auditStatus = '';
      this.toExamineForm.auditCause = '';
    }
  }
};
</script>

<style scoped>
.reject {
    color: #dd6161;
}

.success {
    color: #67c23a;
}
.red {
    color: #fd4e40;
}
.newForm .title {
    width: 300px;
}
.toExamineDialog .el-form-item {
    /* width: 100%; */
}
.el-form .btn_box {
    width: 400px;
    text-align: right;
}
.el-dialog .el-form /deep/ .el-textarea {
    position: unset;
    width: 400px;
    height: 100px;
}
.el-dialog /deep/.el-dialog__body {
    padding: 20px;
}
.el-dialog .el-form /deep/.el-textarea__inner {
    min-height: 100px !important;
}
.el-form .btn_box .el-button {
    width: 85px;
}
.el-table {
    height: 82%;
    font-size: 14px;
}
.el-table /deep/ td,
.el-table /deep/ th {
    text-align: center;
}

.auth_box {
    margin-bottom: 20px;
    text-align: right;
}
.auth_box .el-button {
    width: 100px;
}
.page {
    width: 100%;
    height: 40px;
    background: #ffffff;
    text-align: center;
    padding-top: 20px;
}
</style>